Kotlin for Android App Development (Jakov Mestrovic's Library) by Peter Sommerhoff

Kotlin for Android App Development (Jakov Mestrovic's Library) by Peter Sommerhoff

Author:Peter Sommerhoff
Language: eng
Format: mobi, epub
Publisher: Addison-Wesley Professional
Published: 2019-10-14T16:00:00+00:00


runBlocking {

val deferred: Deferred<Int> = async { throw Exception("Failed...") }

try {

deferred.await() // Tries to get result of asynchronous call, throws exception

} catch (e: Exception) {

// Handle failure case here

}

}

You can also check the state of a Deferred directly using the properties isCompleted and isCompletedExceptionally. Be aware that the latter being false does not mean the operation completed successfully, it may instead still be active. In addition to these, there is also a deferred.invokeOnCompletion callback in which you may use deferred.getCompletionExceptionOrNull to get access to the thrown exception. In most cases, the approach in Listing 6.25 should suffice and is more readable.

Note

Notice the similar relations between launch/join and async/await. Both launch and async are used to start a new coroutine that performs work in parallel. With launch, you may wait for completion using join, whereas with async, you normally use await to retrieve the result.

While launch returns a Job, async returns a Deferred. However, Deferred implements the Job interface so you may use cancel and join on a Deferred as well, although this is less common.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.